#include "abclistviewbar.h"
#include "common/tdebug.h"



#ifdef STRABC
static const char *mCharPersian[]= //1+32个波斯语字母
{"*","ئ","ا","ب","ت","ث","ج","ح","خ","د","ذ","ر","ز","س","ش","ص","ض","ط","ظ","ع","غ","ف","ق","ل","م","ن","ه","و","پ","چ","ک","گ","ی"};
static const char * mCharEnglish[]= //1+26个英文字母
{"*","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",0};
#else
const char ABCListViewBar::mChar[]=CHAR_LIST;
#endif


ABCListViewBar::ABCListViewBar(QWidget *parent) :
    QWidget(parent)
{
    OnInitWidget();

#ifdef STRABC
    if(this->locale()==QLocale::Persian)
    {
        mChar = mCharPersian;
        CHAR_NUM = 32+1; //伊朗语字母数 +*
    }
    else
    {
        mChar = mCharEnglish;
        CHAR_NUM = 26+1; //英文字母数 +*
    }
#else
#endif
}

void ABCListViewBar::OnInitWidget()
{
    mCurIdx = -1;
}


void ABCListViewBar::paintEvent(QPaintEvent *event)
{

    Q_UNUSED(event);
    QPainter painter(this);
    mCharHeight = ((float)height())/CHAR_NUM;
    painter.save();
    OnDrawBar(painter);
    painter.restore();
    QWidget::paintEvent(event);
}

void ABCListViewBar::OnDrawBar(QPainter &painter)
{
    int offsetY = 0;

    QRect rect = QRect(this->pos(),QSize(width(),mCharHeight));
    QFont f("DejaVu Sans");
    f.setPixelSize(mCharHeight-2);
    painter.setFont(f);

    for (int i = 0; i < CHAR_NUM; i++)
    {
#ifdef STRABC
        QString string = mChar[i];
#else
        QString string = QString(mChar[i]);
#endif
        if(i == mCurIdx)
        {
            painter.setPen(QColor(110,180,0));
        }
        else
        {
            painter.setPen(QColor(255,255,255));
        }
        rect.setTop( (int)(i*mCharHeight+0.5) + offsetY );
        rect.setBottom( (int)((i+1)*mCharHeight+0.5)+ offsetY );
        painter.drawText(rect,Qt::AlignCenter,string);

    }
}

void ABCListViewBar::mousePressEvent(QMouseEvent *event)
{
    int y = event->y();
    mCurIdx = y / mCharHeight;
    if (mCurIdx >= CHAR_NUM-1)
    {
        mCurIdx = CHAR_NUM-1;
    }
    else if (mCurIdx < 0)
    {
        mCurIdx = 0;
    }
    update();

    emit ABCChanged(mChar[mCurIdx]);
    emit ABCTipStart();
}

void ABCListViewBar::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    //mCurIdx = -1;
    update();
    emit ABCTipEnd();
}

void ABCListViewBar::mouseMoveEvent(QMouseEvent *event)
{
    int y = event->y();
    int idx = y / mCharHeight;
    if(idx != mCurIdx)
    {
        mCurIdx = idx;
        if (mCurIdx >= CHAR_NUM-1)
        {
            mCurIdx = CHAR_NUM-1;
        }
        else if (mCurIdx < 0)
        {
            mCurIdx = 0;
        }
        update();

        emit ABCChanged(mChar[mCurIdx]);
    }
}
